<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入活动名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="参与企业名称" prop="enterPrizeName">
        <el-input
          v-model="queryParams.enterpriseNames"
          placeholder="企业名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
            >{{ dict.dictLabel }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:enter-service-registration:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:enter-service-registration:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:enter-service-registration:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="announcementList"
      @selection-change="handleSelectionChange"
      stripe
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="活动名称" align="center" prop="name" />
      <el-table-column
        header-align="center"
        align="center"
        prop="enterpriseNames"
        label="企业名称"
      >
        <template slot-scope="scope">
          <span v-for="(name, index) in scope.row.enterpriseNames" :key="index">
            {{ name
            }}<span v-if="index < scope.row.enterpriseNames.length - 1"
              >,
            </span>
          </span>
        </template>
      </el-table-column>

      <el-table-column width="150px" label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <div>
            <!-- 主类型标签 -->
            <el-tag v-if="scope.row.type === 1" type="success">
              中小企业孵化
              <template v-if="scope.row.subtype">
                / {{ getSubTypeLabel(scope.row.type, scope.row.subtype) }}
              </template>
            </el-tag>

            <el-tag v-if="scope.row.type === 2" type="warning">
              高新技术企业培育
              <template v-if="scope.row.subtype">
                / {{ getSubTypeLabel(scope.row.type, scope.row.subtype) }}
              </template>
            </el-tag>

            <el-tag v-if="scope.row.type === 3">
              科技信息查询
              <template v-if="scope.row.subtype">
                / {{ getSubTypeLabel(scope.row.type, scope.row.subtype) }}
              </template>
            </el-tag>

            <el-tag v-if="scope.row.type === 4" type="danger">
              技术服务与咨询
              <template v-if="scope.row.subtype">
                / {{ getSubTypeLabel(scope.row.type, scope.row.subtype) }}
              </template>
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        width="200px"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:enter-service-registration:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:enter-service-registration:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <el-dialog
      :title="title"
      :visible.sync="open"
      width="80%"
      :before-close="handleClose"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <web-editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              >{{ dict.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="服务子类" prop="subtype" v-if="form.type === '1'">
          <el-select
            v-model="form.subtype"
            placeholder="请选择服务子类"
          >
            <el-option
              v-for="item in subTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="选择企业" prop="enterpriseNames">
          <el-select
            v-model="form.enterpriseNames"
            filterable
            placeholder="请选择企业"
            multiple
          >
            <el-option
              v-for="enterprise in enterpriseOptions"
              :key="enterprise.id"
              :label="enterprise.name"
              :value="enterprise.name"
            ></el-option>
            <el-pagination
              :current-page.sync="selectPage.page"
              :page-size="selectPage.size"
              layout="total, prev, pager, next"
              :total="selectPage.total"
              @current-change="getEnterpriseOptions"
            >
            </el-pagination>
          </el-select>
        </el-form-item>

        <el-form-item label="上传附件" prop="attach">
          <el-upload
            class="upload-demo"
            action="/prod-api/file/upload"
            :on-remove="handleRemove"
            :on-change="handleChange"
            multiple
            :limit="10"
            :on-exceed="handleExceed"
            :file-list="uploadedFileList"
            :headers="{ Authorization: getToken() }"
            :on-preview="handlePreview"
            :auto-upload="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { uploadFile } from "@/api/system/file.js";
import { getEnterprise, listEnterprise } from "@/api/system/enterprise";
import {
  addEnterpriseActivity,
  delEnterpriseActivity,
  getEnterpriseActivity,
  listEnterpriseActivity,
  updateEnterpriseActivity,
} from "@/api/system/enter-service-registration";
import { getDicts } from "@/api/system/dict/data";
import { cacheData } from "../../../utils/cache";

export default {
  name: "EnterServiceRegistration",
  data() {
    // 内容校验规则
    const validateContent = (rule, value, callback) => {
      if (!value) {
        callback(new Error('内容不能为空'));
        return;
      }

      // 检查是否有任何HTML内容(包括图片等)
      const hasHtmlContent = value && value.trim().length > 0;

      // 检查去除标签后是否还有文本内容
      const strippedContent = value.replace(/<[^>]+>/g, '').trim();

      // 检查是否包含图片或其他重要元素
      const hasImageOrMedia = /<(img|video|audio)\s+[^>]*>/i.test(value);

      if (!strippedContent && !hasImageOrMedia) {
        callback(new Error('内容不能为空'));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      announcementList: [],
      title: "",
      open: false,
      queryParams: {
        current: 1,
        size: 10,
        name: null,
        content: null,
        enterpriseNames: null,
        type: null,
      },

      form: {
        id: null,
        name: null,
        content: null,
        type: null,
        subtype: null,
        files: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        enterpriseNames: [], // 修改为数组
        displaySubType: "", // 用于显示的值
      },
      rules: {
        name: [
          { required: true, message: "活动名称不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, validator: validateContent, trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择活动类型", trigger: "change" },
        ],
        subtype: [
          { required: true, message: "请选择服务子类", trigger: "change" },
        ],
        enterpriseNames: [
          { required: true, message: "请选择企业", trigger: "change" },
        ],
      },
      enterpriseOptions: [],
      fileList: [],
      uploadedFileList: [],
      subTypeOptions: [
        { label: "创业孵化基金活动", value: "1-1" },
        { label: "工商登记", value: "1-2" },
        { label: "税务登记", value: "1-3" },
        { label: "创新基金申报", value: "1-4" },
        { label: "专利申报", value: "1-5" },
        { label: "企业培训", value: "1-6" },
        { label: "人才招聘", value: "1-7" },
        { label: "投融资咨询", value: "1-8" },
      ],
      typeOptions: [
        { dictValue: "1", dictLabel: "中小企业孵化" },
        { dictValue: "2", dictLabel: "高新技术企业培育" },
        { dictValue: "3", dictLabel: "科技信息查询" },
        { dictValue: "4", dictLabel: "技术服务与咨询" },
      ],
      selectPage: {
        page: 1,
        size: 10,
        total: 0,
      },
    };
  },
  created() {
    this.getList();
    this.getEnterpriseOptions();
    this.getDicts("enterprise_activity").then((res) => {
      this.typeOptions = res.data;
    });
  },
  methods: {
    getSubTypeLabel(type, subtype) {
      const option = this.subTypeOptions.find(
        (opt) => opt.value === `${type}-${-subtype}`
      );
      return option ? option.label : "";
    },
    handleClose(done) {
      this.$confirm("确认关闭该对话框吗？已修改数据将不会保存!")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    getToken() {
      return getToken();
    },
    handleChange(file, fileList) {
      this.fileList.push(file.raw);
    },
    handleRemove(file, fileList) {
      let index = this.fileList.indexOf(file.raw);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
      let exitsIndex = this.uploadedFileList.findIndex(
        (item) => item.uid === file.uid
      );
      if (exitsIndex !== -1) {
        this.uploadedFileList.splice(exitsIndex, 1);
      }
    },
    handlePreview(file) {
      if (file.url) {
        const link = document.createElement("a");
        document.body.appendChild(link);
        link.style.display = "none";
        link.href = file.url;
        link.target = "_blank";
        link.click();
        document.body.removeChild(link);
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    getList() {
      this.loading = true;
      listEnterpriseActivity(this.queryParams).then((response) => {
        this.announcementList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    getEnterpriseOptions() {
      listEnterprise({ current: this.selectPage.page, size: this.selectPage.size }).then((data) => {
        this.selectPage.total = data.data.total;
        this.enterpriseOptions = data.data.records;
      })
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        name: null,
        content: null,
        type: null,
        subtype: null,
        files: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        enterpriseNames: [], // 修改为数组
      };
      this.fileList = [];
      this.uploadedFileList = [];
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "登记活动";
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getEnterpriseActivity(id).then((response) => {
        this.form = response.data;
        this.form.displaySubType = response.data.subtype;
        this.uploadedFileList = response.data.files ?? [];
        this.open = true;
        this.title = "修改文章";
      });
    },
    submitForm() {
      this.form.type = Number(this.form.type);
      this.form.content = this.processContent(this.form.content);

      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          this.form.files = this.uploadedFileList;
          for (const file of this.fileList) {
            const formData = new FormData();
            formData.append("file", file);
            try {
              const res = await uploadFile(formData);
              if (res.code === 200) {
                const { name, url } = res.data;
                this.form.files.push({ name, url });
              }
            } catch (error) {
              this.$modal.msgError("文件上传失败");
              console.error("File upload error:", error);
              return;
            }
          }
          try {
            if (this.form.id != null) {
              await updateEnterpriseActivity(this.form);
              this.$modal.msgSuccess("修改成功");
            } else {
              await addEnterpriseActivity(this.form);
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          } catch (error) {
            this.$modal.msgError(error.message || "提交失败");
            console.error("Form submission error:", error);
          }
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm("是否确认删除所选的登记服务？")
        .then(function () {
          return delEnterpriseActivity(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    handleTypeChange(value) {
      this.form.subtype = null;
    },
    handleSubTypeChange(value) {
      const [parent, child] = value.split("-").map(Number);
      this.form.subtype = -child;
      // 设置显示值为对应的 label
      const selectedOption = this.subTypeOptions.find(
        (opt) => opt.value === value
      );
      if (selectedOption) {
        this.form.displaySubType = selectedOption.label;
      }
      console.log("In index.vue this.form.subType::: ", this.form.subtype);
      console.log("Display value::: ", this.form.displaySubType);
    },
    isHtmlContent(content) {
      const htmlRegex = /<[a-z][\s\S]*>/i;
      return htmlRegex.test(content);
    },
    processContent(content) {
      if (this.isHtmlContent(content)) {
        return content;
      }
      return this.escapeHTML(content);
    },
    escapeHTML(text) {
      return text
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;");
    },
  },
};
</script>
